#!/usr/bin/python
# -*- coding:utf-8 -*-
# @Time  : 6/3/20
# @Author: yanlh
# @usage : SSH不在容器中运行
import sys

sys.path.append('..')
from common_utils import CBBCommonUtils
import docker_utils


def get_plugin_info():
    plugin_info = {
        "name": "Docker_daemon_004 SSH",
        "plugin_id": "docker_daemon_004",
        "plugin_type": "Docker_Daemon_Config_Safe",
        "info": "Ensure sshd is not run within containers",
        "level": "B",
        "module": "Safety scan",
        "author": "yanlh",
        "keyword": "Safety scan",
        "configable": "false",
    }
    return plugin_info


logger = None
cur_user = None
cur_module = None
cur_task = None


def set_plugin_logger(setter, user, module, task, *args, **kwargs):
    global logger, cur_user, cur_module, cur_task
    logger = setter
    cur_user = user
    cur_module = module
    cur_task = task


def single_logger_record(level, des, module='_Scan'):
    if level == 'error':
        logger.debug_error(cur_user, cur_module, cur_task + module, '', des)
    if level == 'info':
        logger.debug_info(cur_user, cur_module, cur_task + module, '', des)
    if level == 'warning':
        logger.debug_warning(cur_user, cur_module, cur_task + module, '', des)


def validate_ssh_service(container, func_args):
    container = container.strip()
    if not container:
        des = 'Docker container is Null.'
        single_logger_record('error', des)
        return des, 1
    cmd = "docker exec {} ps -el |grep -w 'sshd' ".format(container)
    result, output = CBBCommonUtils.cbb_run_cmd(func_args['ip'], cmd, username=func_args['username'],
                                                passwd=func_args['passwd'])
    if result:
        des = "CMD process ERROR. Error info: {}".format(result)
        single_logger_record('error', des)
        return des, 1
    if output and len(output):
        des = 'Not Safe. sshd is run within container {}'.format(container)
        single_logger_record('warning', des)
        return des, 1
    else:
        des = 'Safe. sshd is not run within container {}'.format(container)
        single_logger_record('info', des)
        return des, 0


# 扫描函数
def scan(func_args, flag=0):
    single_logger_record('info', "Scan Start.")
    is_valid, result = docker_utils.validate_daemon_process_running(func_args)
    if not is_valid:
        single_logger_record('error', result)
        return [result], 1
    scan_list = []
    error_count = 0
    for container in result:
        des, error = validate_ssh_service(container, func_args)
        scan_list.append(des)
        error_count = error_count + error
    scan_list.append('Scan Complete.')
    single_logger_record('info', 'Scan Complete.')
    if flag:
        info = ['Please check and config the unsafe item manually.', 'Reinforce Complete.']
        single_logger_record('info', "Reinforce Complete.", '_Reinforce')
        scan_list.extend(info)
        return scan_list, error_count
    return scan_list, error_count


# 回滚函数
def rollback(func_args):
    des_list = ["This function don't need to rollback.", 'Rollback Complete.']
    single_logger_record('info', "Rollback Complete.", '_Rollback')
    return des_list, 0


def check(ip, *args, **kwargs):
    sys_user = kwargs.get("system_user")
    sys_pwd = kwargs.get("system_pwd")
    comm = kwargs.get("command")
    try:
        single_logger_record('info', "docker_daemon_004 Start.", '_Check')
        func_args = {'ip': ip, 'username': sys_user, 'passwd': sys_pwd, 'comm': comm}
        result = docker_utils.check_func(scan, rollback, func_args)
        single_logger_record('info', "docker_daemon_004 Complete.", '_Check')
        return result
    except Exception as er:
        code = 1
        des = ["ERROR:", str(er)]
        single_logger_record('error', des, '_Check')
        return {"code": code, "count": 0, "des": des}


if __name__ == '__main__':
    """
    本地测试
    """
    check(ip=None, command=1)
